package org.ly.dq.module;

import org.apache.commons.lang3.StringUtils;
import org.ly.dq.bean.PingPai;
import org.ly.dq.bean.ShiFu;
import org.ly.dq.bean.WeiXiu;
import org.ly.dq.bean.WeiXiuDate;
import org.ly.utils.WeiXiuDateUtil;
import org.ly.utils.fileUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.service.EntityService;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@At("/AnZhuang")
@IocBean(fields = {"dao"})
public class AnZhuangModule extends EntityService<WeiXiu> {

    private static final Log log = Logs.get();

    @At
    @Ok("jsp:views.dq.listAnZhuang")
    public Object list(@Param("page") int page, @Param("rows") int rows, @Param("::params.") Map<String, String> params, HttpServletRequest request) {

        Criteria cri = Cnd.cri();
        List<PingPai> pingPais = null;
        List<WeiXiu> list = null;
        Criteria uCri = Cnd.cri();
        uCri.where().and("userName","=", Mvcs.getHttpSession().getAttribute("username").toString());
        Map<String,Object> rMap = getpingPais(uCri,dao());
        pingPais = (List<PingPai>)rMap.get("pingPais");
        String[] names = (String[])rMap.get("names");
 
        if (rows < 1)
            rows = 10;
        if (page < 1)
            page = 1;
        if (params != null) {
        	
        	//维修状态 
        	if(StringUtils.isNoneEmpty(params.get("wxZhuangTai"))){
        		 cri.where().and("zhuangTai", "=" , params.get("wxZhuangTai"));
        	}
            //订单号
            if (StringUtils.isNotEmpty(params.get("dingDanHao"))) {
                cri.where().andLike("dingDanHao", params.get("dingDanHao"));
            }
            //维修人
            if (StringUtils.isNotEmpty(params.get("weiXiuRen"))) {
                cri.where().andLike("weiXiuRen", params.get("weiXiuRen"));
            }
            //用户姓名
            if (StringUtils.isNotEmpty(params.get("yongHuName"))) {
                cri.where().andLike("yongHuName", params.get("yongHuName"));
            }
            //用户电话
            if (StringUtils.isNotEmpty(params.get("yongHuPhone"))) {
                cri.where().andLike("yongHuPhone", params.get("yongHuPhone"));
            }
            //品牌号
            if (StringUtils.isNotEmpty(params.get("pingPaiHao"))) {
                cri.where().andLike("pingPaiHao", params.get("pingPaiHao"));
            } /*else {
                if(!Mvcs.getHttpSession().getAttribute("username").equals("admin") & names.length != 0){
                    cri.where().andIn("pingPaiHao", names);
                }

            }*/
            //保修日期（截止日期）
            if (StringUtils.isNotEmpty(params.get("ebaoXiuRiQi"))) {
                cri.where().and("baoXiuRiQi", "<=", params.get("ebaoXiuRiQi"));
            }
            //保修日期（开始日期）
            if (StringUtils.isNotEmpty(params.get("nbaoXiuRiQi"))) {
                cri.where().and("baoXiuRiQi", ">=", params.get("nbaoXiuRiQi"));
            }
            //内机条码
            if (StringUtils.isNotEmpty(params.get("tiaoMa"))) {
                cri.where().andLike("tiaoMa", params.get("tiaoMa"));
            }
            //外机条码
            if (StringUtils.isNotEmpty(params.get("waiJiTiaoMa"))) {
                cri.where().andLike("waiJiTiaoMa", params.get("waiJiTiaoMa"));
            }
        } /*else {
            if(!Mvcs.getHttpSession().getAttribute("username").equals("admin") & names.length != 0){
                cri.where().andIn("pingPaiHao", names);
            }
        }*/


        //非超级用户拥有品牌的数据
        if(!Mvcs.getHttpSession().getAttribute("username").equals("admin") & names.length != 0) {
            cri.where().andIn("pingPaiHao", names);
        }


        Pager pager = dao().createPager(page, rows);
        // 登陆用户没有拥有品牌部查询数据
        if(!Mvcs.getHttpSession().getAttribute("username").equals("admin") & names.length == 0){
            list = null;
        }else {
            list = dao().query(WeiXiu.class, cri, pager);
        }
        //超级用户查询所有数据
        if(Mvcs.getHttpSession().getAttribute("username").equals("admin")){
            list = dao().query(WeiXiu.class, cri, pager);
            pingPais = dao().query(PingPai.class,null);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (pager != null) {
            int cont = dao().query(WeiXiu.class, cri, null).size();
            pager.setRecordCount(cont <= 0 ? 1 : cont);
            map.put("pager", pager);
        }
        List<ShiFu> shiFus = dao().query(ShiFu.class, null);
        map.put("shiFus", shiFus);
        map.put("pingPais", pingPais);
        List<WeiXiuDate> weiXiuDates = WeiXiuDateUtil.getWeiXiuDates(list,dao());
        map.put("list", weiXiuDates);
        map.put("params", params);
        map.put("url", request.getRequestURL());
        return map;
    }

    @At
    @Ok("jsp:views.dq.addAnZhuang")
    public Object add() {
        Map<String, Object> map = new HashMap<String, Object>(0);
        List<ShiFu> shiFus = dao().query(ShiFu.class, null);
        List<PingPai> pingPais = dao().query(PingPai.class, null);
        map.put("shiFus", shiFus);
        map.put("pingPais", pingPais);
        return map;
    }

    @At
    @Ok("redirect:/AnZhuang/list?params.wxZhuangTai=1")
    @AdaptBy(type = UploadAdaptor.class, args = {"${app.root}/tmp"})
    public void save(@Param("..") WeiXiu obj, @Param("file") TempFile[] files) {
        File f1 = null;
        String Path = Mvcs.getServletContext().getRealPath("/upload");
        String Name = System.currentTimeMillis() + "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            Date date = new Date();
            obj.setBaoXiuRiQi(date);
            obj.setDingDanHao(sdf.format(date));
            obj.setLuRuRen(Mvcs.getHttpSession().getAttribute("username").toString());
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    switch (i) {
                        case 0:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian1(Name);
                            break;
                        case 1:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian2(Name);
                            break;
                        case 2:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian3(Name);
                            break;
                    }
                }
            }
            dao().insert(obj);
        } catch (Throwable e) {
            if (log.isDebugEnabled())
                log.debug("E!!", e);
        }
    }

    @At
    @Ok("redirect:/AnZhuang/list?params.wxZhuangTai=1")
    public boolean delete(@Param("..") WeiXiu obj) {
        try {
            dao().delete(obj);
            return true;
        } catch (Throwable e) {
            if (log.isDebugEnabled())
                log.debug("E!!", e);
            return false;
        }
    }

    @At
    @Ok("redirect:/AnZhuang/list?params.wxZhuangTai=2")
    public void ok(@Param("weiXiuId") Integer weiXiuId) {
        WeiXiu weiXiu = dao().fetch(WeiXiu.class, weiXiuId);
        weiXiu.setZhuangTai(2+"");
        dao().update(weiXiu);
    }


    @At
    @Ok("jsp:views.dq.addAnZhuang")
    public Object edit(@Param("weiXiuId") Integer weiXiuId) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        WeiXiu weiXiu = dao().fetch(WeiXiu.class, weiXiuId);
        List<ShiFu> shiFus = dao().query(ShiFu.class, null);
        List<PingPai> pingPais = dao().query(PingPai.class, null);
        map.put("shiFus", shiFus);
        map.put("pingPais", pingPais);
        map.put("weixiu", weiXiu);
        map.put("flag", "edit");
        return map;
    }


    @At
    @Ok("jsp:views.dq.viewAnZhuang")
    public Object view(@Param("weiXiuId") Integer weiXiuId) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        WeiXiu weiXiu = dao().fetch(WeiXiu.class, weiXiuId);
        map.put("weixiu", weiXiu);
        return map;
    }


    @At
    @Ok("redirect:/AnZhuang/list?params.wxZhuangTai=1")
    @AdaptBy(type = UploadAdaptor.class, args = {"${app.root}/tmp"})
    public void update(@Param("..") WeiXiu obj, @Param("file") TempFile[] files) {
        File f1 = null;
        String Path = Mvcs.getServletContext().getRealPath("/upload");
        String Name = System.currentTimeMillis() + "";
        try {
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    switch (i) {
                        case 0:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian1(Name);
                            break;
                        case 1:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian2(Name);
                            break;
                        case 2:
                            Name += files[i].getFile().getName();
                            f1 = new File(Path + "\\" + Name);
                            fileUtil.forTransfer(files[i].getFile(), f1);
                            obj.setTuPian3(Name);
                            break;
                    }
                }
            }
            dao().update(obj);
        } catch (Throwable e) {
            if (log.isDebugEnabled())
                log.debug("E!!", e);
        }
    }


    /**
     *
     * @param uCri Criteria
     * @param dao  Dao
     * @return names 品牌名
     */
    protected Map<String,Object> getpingPais(Criteria uCri, Dao dao){
        List<PingPai> pingPais = dao.query(PingPai.class, uCri);
        String[] names = new String[pingPais.size()];
        for (int i=0; i<pingPais.size(); i++){
            names[i] = pingPais.get(i).getPingPaiName();
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("names",names);
        map.put("pingPais",pingPais);
        return map;
    }
}